import { Controller, Post, Body, Get, Param, Delete, Put, UseGuards, UseInterceptors, UploadedFiles } from '@nestjs/common';
import { QuestionsService } from './questions.service';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { RolesGuard } from '../auth/guards/roles.guard';
import { Roles } from '../auth/roles.decorator';
import { FilesInterceptor } from '@nestjs/platform-express';
import { diskStorage } from 'multer';
import * as path from 'path';
import { generateUniqueFilename } from '../utils/filename.util';
const uploadPath = path.resolve(__dirname, '../../uploads');
import { customAlphabet } from 'nanoid';
import { CreateQuestionDto } from './dto/create-question.dto';
@Controller('questions')
@UseGuards(JwtAuthGuard, RolesGuard)
export class QuestionsController {
  constructor(private readonly questionsService: QuestionsService) {}

  @Post()
  @Roles('ADMIN')
  @UseInterceptors(FilesInterceptor('images', null, {
    storage: diskStorage({
      destination: uploadPath,
      filename: (req, file, cb) => {
        cb(null, generateUniqueFilename(file.originalname));
      },
    })
  }))
  async create(@Body() createQuestionDto: CreateQuestionDto) {
    // 确保 correctAnswer 是数组形式
    if (createQuestionDto.correctAnswer && !Array.isArray(createQuestionDto.correctAnswer)) {
      createQuestionDto.correctAnswer = [createQuestionDto.correctAnswer];
    }
    
    return this.questionsService.create(createQuestionDto);
  }

  @Get(':id')
  async findOne(@Param('id') id: string) {
    return this.questionsService.findOne(id);
  }

  @Put(':id')
  @Roles('ADMIN')
  @UseInterceptors(FilesInterceptor('images', null, {
    storage: diskStorage({
      destination:  uploadPath,
      filename:(req, file, cb) => {
        cb(null, generateUniqueFilename(file.originalname));
      },
    })
  }))
  async update(
    @Param('id') id: string,
    @UploadedFiles() files: Express.Multer.File[],
    @Body() updateQuestionDto: any
  ) {
    return this.questionsService.update(id, updateQuestionDto, files);
  }

  @Delete(':id')
  @Roles('ADMIN')
  async remove(@Param('id') id: string) {
    return this.questionsService.remove(id);
  }
  @Get('by-material/:materialId')
async findByMaterial(@Param('materialId') materialId: string) {
  return this.questionsService.findByMaterialId(materialId);
}
// 同时获取多个题目
@Post('by-ids')
async findByIds(@Body('ids') ids: string[]) {
  return this.questionsService.findByIds(ids);
}
}